import React, { useState, useRef, useEffect } from 'react';
import './VoiceMessage.less';
import { useVoiceAssistant, useVoiceRecognition} from './hooks';
import {  message } from 'antd';
interface VoiceMessageProps {
  onSend: (content: string, isVoice?: boolean) => void;
  showInputText:(show: boolean) => void;
}

const VoiceMessage: React.FC<VoiceMessageProps> = ({ onSend, showInputText }) => {
  const [isRecording, setIsRecording] = useState(false);
  const [recordTime, setRecordTime] = useState(0);
  const [voiceText, setVoiceText] = useState('');
  const [showCancel, setShowCancel] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const timerRef = useRef<NodeJS.Timeout>();
  const touchStartRef = useRef<number>(0);
  const voiceRef = useRef<HTMLDivElement>(null);
   // 使用语音助手钩子，替代原来的状态管理
  const { isEnabled, toggleVoiceAssistant, startRecognize, stopRecognize} = useVoiceAssistant();

  // 开始录音
  const startRecording = (e: React.TouchEvent | React.MouseEvent) => {
    e.preventDefault();
    setIsRecording(true);
    setRecordTime(0);
    setVoiceText('');
    touchStartRef.current = Date.now();
    
    // 模拟语音识别开始
    console.log('开始录音');
    
    // 计时器
    timerRef.current = setInterval(() => {
      setRecordTime(prev => prev + 1);
      
      // // 模拟语音转文字结果
      // if (recordTime % 3 === 0) {
      //   setVoiceText(prev => prev + ' 测试语音转文字');
      // }
    }, 1000);
   
    // 和app交互，唤起app测的语音识别  
    try {
      // toggleVoiceAssistant(); // 开始录音之前先检查开启
      message.error('开启录音...');
      startRecognize()
    } catch (error) {
      console.error('语音输入失败:', error);
    }
  };

  // 使用语音识别钩子，将识别到的文字展示在输入框中
  // useVoiceRecognition((recognizedText, type) => {
  //   message.error('语音识别中...'+recognizedText);
  //   // console.log('recognizedText', recognizedText);
  //   console.log('type', type);
  //   setVoiceText(recognizedText);
   
  // });

  // 结束录音
  const endRecording = () => {
    if (!isRecording) return;
    
    clearInterval(timerRef.current);
    setIsRecording(false);
    stopRecognize()
    
    const duration = Date.now() - touchStartRef.current;
    
    // 长按时间足够才发送
    if (duration > 500 && !showCancel) {
      if (voiceText.trim()) {
        onSend(voiceText, false); // 发送文字
      } else {
        onSend(`${recordTime}s语音`, true); // 发送语音
      }
    }
    // toggleVoiceAssistant(); // 关闭语音助手 如果没有成功，则switch开关状态不变
    setRecordTime(0);
    setShowCancel(false);
  };

  // 取消录音
  const cancelRecording = () => {
    clearInterval(timerRef.current);
    setIsRecording(false);
    setRecordTime(0);
    setShowCancel(false);
    console.log('取消发送');
  };

  // 触摸移动处理（判断是否取消）
  const handleTouchMove = (e: React.TouchEvent) => {
    if (!isRecording) return;
    
    const touch = e.touches[0];
    const { clientY } = touch;
    const { top, height } = voiceRef.current?.getBoundingClientRect() || { top: 0, height: 0 };
    const threshold = height * 0.7;
    
    setShowCancel(clientY < top - threshold);
    setPosition({ x: touch.clientX, y: touch.clientY });
  };
  const handeKey = () => {
    console.log('handeKey')
    showInputText(true)
  }
  // 清理计时器
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);
  return (
    <div className="voice-message-container">
      {isRecording && (
        <div className={`voice-recording-modal ${showCancel ? 'cancel-mode' : ''}`}>
          <div className="voice-recording-content">
            {showCancel ? (
              <div className="cancel-tip">松开手指，取消发送</div>
            ) : (
              <>
                <div className="recording-icon">
                  <div className="voice-wave">
                    {[1, 2, 3, 4, 5].map((i) => (
                      <div 
                        key={i}
                        className="wave-bar"
                        style={{ 
                          animationDelay: `${i * 0.1}s`,
                          height: `${Math.random() * 60 + 20}%`
                        }}
                      />
                    ))}
                  </div>
                </div>
                <div className="recording-time">{recordTime}s</div>
                {/* {voiceText && <div className="voice-text-preview">{voiceText}</div>} */}
              </>
            )}
          </div>
        </div>
      )}
      <div className='keyIcon' onClick={()=>{showInputText(false);setIsRecording(false)}}>返回</div>
      <div
        className={`voice-button ${isRecording ? 'recording' : ''}`}
        onTouchStart={startRecording}
        onMouseDown={startRecording}
        onTouchEnd={endRecording}
        onMouseUp={endRecording}
        onTouchMove={handleTouchMove}
        onMouseLeave={endRecording}
        ref={voiceRef}
      >
        {isRecording ? '松开 结束' : '按住 说话'}
      </div>
    </div>
  );
};

export default VoiceMessage;